//
//  RecordManager.m
//  record_plugin
//
//  Created by 3tee on 2024/9/24.
//

#import "RecordManager.h"
#import "SingleRecordVC.h"
#import "DoubleRecordPrepareVC.h"
#import "Constant.h"

@interface RecordManager ()<AVDEngineDelegate,AVDRoomJoinDelegate,SingleRecordDelegate>

@property(nonatomic, weak)id<RecordManagerDelegate> delegate;
@property (strong, nonatomic) NSString * roomID;
@property (strong, nonatomic) NSString * userID;
@property (strong, nonatomic) NSString * avdToken;
@property (strong, nonatomic) NSString * accessToken;
@property (strong, nonatomic) NSString * avdUrl;
@property (nonatomic, strong) AVDRoom *mRoom;
@property (nonatomic, strong) NSMutableArray<TTSModel *> *mTssArr;

@end

@implementation RecordManager

static RecordManager *_sharedInstance = nil;

- (void)dealloc{
    NSLog(@"RecordManager ==== dealloc");
}
 
+ (RecordManager *)sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[self alloc] init];
    });
    return _sharedInstance;
}

- (void)initWithServerPath:(NSString *)serverPath delegate:(id<RecordManagerDelegate>)delegate{
    self.delegate = delegate;
    [[NetworkingTool sharedInstance] getAuthTokenWithServerPath:serverPath handler:^(NSString * _Nonnull accessToken) {
        [self getAVDServer];
    } failure:^(NSError * _Nonnull error) {
        [self callBack:@"-1" msg:@"获取oauthToken失败"];
    }];
  
    
}

- (void)startRecord:(NSString *)firstFile similarity:(double)similarity product:(NSString *)productCode navigationController:(UINavigationController *)navigationController{

    NSBundle *SDKBundle = [NSBundle bundleForClass:[SingleRecordVC class]];
    SingleRecordVC * vc = [[SingleRecordVC alloc] initWithNibName:@"SingleRecordVC" bundle:SDKBundle];
    vc.productCode = productCode;
    vc.similarity = similarity;
    vc.delegate = self;
    vc.firstFileUrl = firstFile;
    vc.roomID = self.roomID;
    vc.userID = self.userID;
    [navigationController pushViewController:vc animated:YES];
}

- (void)remote:(NSInteger)productId customerName:(NSString *)name phone:(NSString *)phone frontCheckFaceScore:(NSString *)score applyId:(NSString *)applyId navigationController:(UINavigationController *)navigationController{
    NSBundle *SDKBundle = [NSBundle bundleForClass:[DoubleRecordPrepareVC class]];
    DoubleRecordPrepareVC * vc = [[DoubleRecordPrepareVC alloc] initWithNibName:@"DoubleRecordPrepareVC" bundle:SDKBundle];
    vc.productId = productId;
    vc.phone = phone;
    vc.customerName = name;
    vc.faceCheckScore = score;
    vc.applyId = applyId;
    [navigationController pushViewController:vc animated:YES];
}

#pragma mark httpReq
- (void)getAVDServer{
    [[NetworkingTool sharedInstance] getAVDServerWithHandler:^(NSString * _Nonnull avdServerUrl) {
        [self getAVDToken:avdServerUrl];
    } failure:^(NSError * _Nonnull error) {
        [self callBack:@"-2" msg:@"获取avdSever失败"];
    }];
    
   
}

- (void)getAVDToken:(NSString *)url{
    [[NetworkingTool sharedInstance] getAVDTokenWithHandler:^(NSString * _Nonnull avdToken) {
        [self initAVDEng:url token:avdToken];
    } failure:^(NSError * _Nonnull error) {
        [self callBack:@"-3" msg:@"获取avdToken失败"];
    }];
}

#pragma mark 音视频
- (void)initAVDEng:(NSString *)url token:(NSString *)token{
    self.avdToken = token;
    self.avdUrl = url;
    [[AVDEngine instance] setLogParams:@"info" file:[self getLogFileName]];
    [[AVDEngine instance] initWithServerUrl:url token:token delegate:self];
}

- (void)createRoom{
    AVDRoomInfo *roomInfo = [[AVDRoomInfo alloc]initWithRoomId:nil roomName:@"record_plugin" appRoomId:nil ownerId:nil maxAttendee:100 maxAudio:100 maxVideo:100 roomMode:1 voiceActivated:YES];
    [roomInfo setRoomModeFlag:mcu];
    [[AVDEngine instance] scheduleRoom: roomInfo];
}

- (void)joinRoom{
    self.mRoom = [AVDRoom obtain:self.roomID];
    self.mRoom.delegate = self;
//    self.mVideo = [AVDVideo getVideo:self.mRoom];
//    self.mVideo.delegate = self;
//    self.mAudio = [AVDAudio getAudio:self.mRoom];
//    self.mAudio.delegate = self;
//    self.mAudioExport = [AVDAudioExport getAudioExport:self.mRoom];
//    self.mAudioExport.delegate = self;
    self.userID = [NSUUID UUID].UUIDString;
    AVDUser *user = [[AVDUser alloc]initWithUserId:self.userID userName:@"record_plugin" userData:nil];
    [self.mRoom joinWithUser:user delegate:self];
}

#pragma mark RoomDelegate
-(void)onJoinResult:(AVDResult)result{
    if (result == AVD_Success) {
        NSLog(@"房间加入成功");
        //[self callBack:@"0" msg:@"录制模块初始化成功"];
    }else{
        NSLog(@"间加入失败");
        [self callBack:@"-6" msg:@"房间加入失败"];
    }
}

#pragma mark EngDelegate
- (void)onInitResult:(AVDResult)result{
    if (result == AVD_Success) {
        NSLog(@"引擎初始化成功");
        [[AVDEngine instance] setOption:camera_capability_default value:@"{\"width\":720,\"height\":1280,\"maxFPS\":15}"];
        [self createRoom];
    }else{
        NSLog(@"引擎初始化失败");
        [self callBack:@"-4" msg:@"音视频初始化失败"];
    }
}

- (void)onScheduleRoomResult:(AVDResult)result roomId:(AVDRoomId)roomId{
    if (result == AVD_Success) {
        NSLog(@"房间创建成功 id = %@",roomId);
        self.roomID = roomId;//@"9164181727344376866";;
        [self callBack:@"0" msg:@"录制模块初始化成功"];

    }else{
        NSLog(@"房间创建失败 code = %ld",result);
        [self callBack:@"-5" msg:@"房间创建失败"];

    }
}

- (NSString*)getLogFileName {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd-HHmmss"];
    NSString *destDateString = [dateFormatter stringFromDate: [NSDate date] ];
    NSString *fileName = [NSString stringWithFormat:@"/%@.txt", destDateString];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDir = [paths objectAtIndex:0];
    docDir = [docDir stringByAppendingString:@"/logs"];
    fileName = [docDir stringByAppendingPathComponent:fileName];
    return fileName;
}

- (void)callBack:(NSString *)code msg:(NSString *)msg{
    if (self.delegate && [self.delegate respondsToSelector:@selector(onInitResult:message:)]) {
        [self.delegate onInitResult:code message:msg];
    }
}

- (void)unInit{
    [[AVDEngine instance] uninit];
}


#pragma singleVC delegate
- (void)onPulishVideoStatus:(BOOL)status{
    if (self.delegate && [self.delegate respondsToSelector:@selector(onRecordResult:message:filePath:)]) {
        [self.delegate onRecordResult:@"0" message:@"视频打开成功" filePath:@""];
    }
}

- (void)onRecordStatus:(NSString *)status msg:(nonnull NSString *)msg  videoUrl:(NSString *)videoUrl{
    if (self.delegate && [self.delegate respondsToSelector:@selector(onRecordResult:message:filePath:)]) {
        [self.delegate onRecordResult:status message:msg filePath:videoUrl];
    }
}

@end
